<template>
  <div class="base-container">
    <t-row>
      <t-col :span="3" style="padding-right: 10px">
        <t-input
          style="margin-bottom: 10px"
          clearable
          placeholder="请输入单位名称"
          v-model="deptName"
          @change="deptNameTreeFilter"
        >
          <template #prefix-icon>
            <t-icon name="search" class="icon" size="16"/>
          </template>
        </t-input>
        <t-tree activable :actived.sync="deptNameTreeValue" :data="deptOptions" :keys="{value:'id'}" @click="handleNodeClick" :expandAll="false" :filter="filterByText" hover :expand-on-click-node="false"  />
      </t-col>
      <t-col :span="9">
        <!-- <t-form ref="form" :data="queryParams" label-width="80" @reset="onReset" @submit="onSubmit">
          <t-row style="border-bottom: 1px solid #E5E6EB;margin-bottom: 10px">
            <t-col :span="11" class="query-form-inline">
              <t-form-item label="登录名称" name="userName">
                <t-input
                  v-model="queryParams.userName"
                  clearable
                  placeholder="请输入用户名称"
                  style="width: 240px"
                />
              </t-form-item>
              <t-form-item label="用户名称" name="nickName">
                <t-input
                  v-model="queryParams.nickName"
                  clearable
                  placeholder="请输入用户名称"
                  style="width: 240px"
                />
              </t-form-item>
              <t-form-item label="手机号码" name="phonenumber">
                <t-input
                  v-model="queryParams.phonenumber"
                  clearable
                  placeholder="请输入手机号码"
                  style="width: 240px"
                />
              </t-form-item>
              <t-form-item label="状态" name="status">
                <t-select style="width: 240px" placeholder="用户状态" :options="dict.type.sys_normal_disable" v-model="queryParams.status" />
              </t-form-item>
            </t-col>
            <t-col :span="1" class="operation-container">
              <t-button theme="primary" type="submit">查询</t-button>
              <t-button theme="default" variant="outline" type="reset">重置</t-button>
            </t-col>
          </t-row>
        </t-form> -->
        <div class="btn-group-inline">
          <t-button v-if="deptNameTreeValue.length>0"  @click="addUser" variant="outline" theme="primary">
            <t-icon name="add" slot="icon"/>
            新增
          </t-button>
          <t-button @click="exportExcel" variant="outline" theme="primary">
            <t-icon name="download" slot="icon"/>
            导出
          </t-button>
        </div>
        <t-table
          rowKey="id"
          :data="data"
          :columns="columns"
          hover
          :pagination="pagination"
          :loading="dataLoading"
        >
          <template #xsProjectCount="{ row }">
            <t-link @click="dialog.header=`${row.userName}-已分配项目`;dialog.userId=row.id;dialog.open_show_approver_project=true" hover="color" theme="primary">{{row.xsProjectCount}}</t-link>
          </template>
          <template #status="{ row }">
            <t-switch @change="handleStatusChange(row)" :value="row.status==='0'">
            </t-switch>
          </template>
          <template #op="{ row }">
            <t-button  @click="updateUser(row.id, row.departmentId)" size="small" variant="text" class="t-button-link">
              <t-icon name="edit-1" slot="icon"/>
              修改
            </t-button>
            <t-button theme="danger"  @click="deleteUser(row.id, row.userName)" size="small" variant="text" class="t-button-link">
              <t-icon name="delete" slot="icon"/>
              删除
            </t-button>
            <t-button @click="dialog.userId=row.id;dialog.userName=row.userName;dialog.open_reset_user_password=true" size="small" variant="text" class="t-button-link">
              <t-icon name="edit-1" slot="icon"/>
              重置密码
            </t-button>
            <t-button  @click="assignmentProject(row)" size="small" variant="text" class="t-button-link">
              <t-icon name="check-circle" slot="icon"/>
              分配项目
            </t-button>
          </template>
        </t-table>
      </t-col>
    </t-row>
    <add-approver @reload="getList()" :header="dialog.header" :userId="dialog.userId" :deptId="dialog.deptId" :visible.sync="dialog.open_add_edit_user" v-if="dialog.open_add_edit_user"></add-approver>
    <reset-user-password :visible.sync="dialog.open_reset_user_password" :userId="dialog.userId" :userName="dialog.userName" v-if="dialog.open_reset_user_password"></reset-user-password>
    <select-approver-project header="分配项目" :visible.sync="dialog.open_select_approver_project" :row="dialog.row" v-if="dialog.open_select_approver_project"></select-approver-project>
    <show-approver-project :header="dialog.header" :userId="dialog.userId" :visible.sync="dialog.open_show_approver_project"
                           v-if="dialog.open_show_approver_project">

    </show-approver-project>
  </div>
</template>

<script>
import AddApprover from './components/add-approver.vue'
import ResetUserPassword from '@/pages/common/system/components/reset-user-password.vue'
import selectApproverProject from "./components/select-approver-project.vue";
import ShowApproverProject from "./components/show-approver-project.vue";

import {
  listUser,
  changeUserStatus,
  delUser
} from "@/api/system/user";
import { treeselect, treeselectParty } from "@/api/system/dept";


export default {
  name: "approver-management",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: {
    AddApprover,
    ResetUserPassword,
    selectApproverProject,
    ShowApproverProject
  },
  data() {
    return {
      deptName: "",
      deptNameTreeValue:[],
      userId:0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // userName: "",
        // nickName: "",
        // phonenumber: "",
        // status: "",
        userType: 2,
        deptId: null,
        dateRange:[]
      },
      data: [],
      deptOptions: undefined,
      filterByText: null,
      columns: [
        // {
        //   colKey: 'row-select',
        //   type: 'multiple',
        //   width: 64,
        // },
        // {
        //   colKey: "id",
        //   title: "用户编号",
        //   align: "center"
        // },
        {
          colKey: "userName",
          title: "登录名称",
          align: "center"
        },
        // {
        //   colKey: "nickName",
        //   title: "真实姓名",
        //   align: "center"
        // },
        {
          colKey: "dept.deptName",
          title: "部门",
          align: "center"
        },
        {
          colKey: "xsProjectCount",
          title: "已分配项目数",
          align: "center",
          width: 120
        },
        {
          colKey: 'effectiveStartDate',
          title: '有效开始时间',
          align: 'center',
          width: 120
        },
        {
          colKey: 'effectiveEndDate',
          title: '有效截止时间',
          align: 'center',
          width: 120
        },
        // {
        //   colKey: "phonenumber",
        //   title: "手机号",
        //   align: "center"
        // },
        // {
        //   colKey: "status",
        //   title: "状态",
        //   align: "center"
        // },
        // {
        //   colKey: "createTime",
        //   title: "创建时间",
        //   align: "center",
        //   width: 200,
        // },
        {
          colKey: "op",
          title: "操作",
          align: "center",
          width: 320
        }
      ],
      dataLoading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showPageSize: true,
        pageSizeOptions: [10,20,30],
        showFirstAndLastPageBtn: false,
        onChange: (pageInfo) => {
          Object.assign(this.pagination,pageInfo)
          this.queryParams.pageNum = pageInfo.current || 1;
          this.queryParams.pageSize = pageInfo.pageSize;
          this.getList()
        },
      },
      dialog: {
        header: "",
        open_add_edit_user: false,
        open_reset_user_password: false,
        open_select_approver_project: false,
        open_show_approver_project: false,
        userId: 0,
        deptId: null,
        userName: "",
        row: null
      }
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    // this.getTreeselectParty();
  },
  methods: {
    exportExcel(){
      this.$download(`/system/user/exportXsList`,this.queryParams, `形式审查人员列表_${new Date().getTime()}.xls`)
    },
    assignmentProject(row){
      this.$router.push({path:`/kjxm/other/approve/user-project/${row.id}`,query:{title:`形式审查项目分配-${row.userName}`}});
    },
    getList(){
      this.dataLoading = true;
      if (this.deptNameTreeValue.length <= 0) {
        this.queryParams.deptId = undefined;
      }
      this.$api.system.user.xsList(this.queryParams).then(
        (res) => {
          this.data = res.rows;
          this.pagination.total = res.total;
          this.dataLoading = false;
        }).catch((e) => {
        this.dataLoading = false;
        this.$message.error(e.toString());
      });
    },
    onSubmit() {
      this.getList();
    },
    onReset(){
      this.queryParams.deptId = undefined;
      this.deptNameTreeValue = [];
    },
    deleteUser(userId, userName){
      const confirmDia = this.$dialog.confirm({
        header:"系统提示",
        body:`是否确认删除用户名称为${userName}的数据项？`,
        theme: "warning",
        onConfirm: () => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          })
          delUser(userId).then(
            () => {
              this.getList();
              this.$message.success("删除成功");
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            }
          ).catch((e) => {
            confirmDia.update({
              confirmBtn: {
                loading: false,
              },
            })
            this.$message.error(e.toString());
          });
        },
      })
    },
    // handleStatusChange(row) {
    //   const text = row.status === "1" ? "启用" : "停用";
    //   const status = row.status === "1" ? "0" : "1";
    //   const confirmDia = this.$dialog.confirm({
    //     header:"系统提示",
    //     body:`确认要${text}"${row.userName}"用户吗？`,
    //     theme: "warning",
    //     onConfirm: ({ e }) => {
    //       changeUserStatus(row.id, status).then(
    //         (res) => {
    //           row.status = status;
    //           this.$message.success(`${text}成功`);
    //           // 请求成功后，销毁弹框
    //           confirmDia.destroy();
    //         }
    //       ).catch((e) => {
    //         this.$message.error(e.toString());
    //       });
    //     },
    //   })
    // },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((res) => {
        this.deptOptions = res.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    /** 查询党组织下拉树结构 */
    getTreeselectParty() {
      treeselectParty().then((res) => {
        this.deptOptionsParty = res.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    addUser() {
      this.dialog.open_add_edit_user = true;
      this.dialog.header='添加用户';
      this.dialog.userId=0;
      this.dialog.deptId=this.queryParams.deptId;
    },
    updateUser(userId, deptId){
      this.dialog.open_add_edit_user=true;
      this.dialog.header='修改用户';
      this.dialog.userId=userId;
      this.dialog.deptId=deptId;
    },
    deptNameTreeFilter(){
      if (this.deptName) {
        // 存在过滤文案，才启用过滤
        this.filterByText = (node) => {
          const rs = node.data.label.indexOf(this.deptName) >= 0;
          // 命中的节点会强制展示
          // 命中节点的路径节点会锁定展示
          // 未命中的节点会隐藏
          return rs;
        };
      } else {
        // 过滤文案为空，则还原 tree 为无过滤状态
        this.filterByText = null;
      }
    },
    handleNodeClick(content) {
      this.queryParams.deptId = content.node.data.id;
      this.dialog.deptId = content.node.data.id;
      this.getList();
      // this.handleQuery();
    },
    handlerUserProject() {
      console.log('分配项目')
    }
  }
}
</script>

<style scoped>
.t-dropdown__item{
  margin:0px;
  padding:0px;
}
</style>
